/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.phoenix.repository;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;

import javax.jcr.RepositoryException;
import javax.jcr.query.Row;

/**
 * Jigsaw server
 * 
 * @author <a href="shamphone@gmail.com">Li XiongFeng</a>
 * @date 2012-4-6
 * @version 1.0.0
 */
public class RowToMap extends AbstractMap<String, Object> {
	private Row row;
	private String[] columns;

	public RowToMap(String[] columns, Row row) {
		this.row = row;
		this.columns = columns;
	}

	public Object get(String key) {
		try {
			return row.getValue(key).getString();
		} catch (RepositoryRuntimeException e) {
			throw e;
		} catch (RepositoryException e) {
			throw new RepositoryRuntimeException(e);
		}
	}

	@Override
	public Set<Entry<String, Object>> entrySet() {
		return new RowSet();
	}

	class RowSet extends AbstractSet<Entry<String, Object>> {

		@Override
		public Iterator<Entry<String, Object>> iterator() {
			return new RowIterator();
		}

		@Override
		public int size() {
			return columns.length;
		}

	}

	class RowIterator implements Iterator<java.util.Map.Entry<String, Object>> {
		private int count = -1;

		public RowIterator() {
			this.count = -1;
		}

		@Override
		public boolean hasNext() {
			return this.count < columns.length - 1;
		}

		@Override
		public Entry<String, Object> next() {
			this.count++;
			return new Entry<String, Object>() {

				@Override
				public String getKey() {
					return columns[count];
				}

				@Override
				public Object getValue() {
					return get(columns[count]);
				}

				@Override
				public Object setValue(Object value) {
					return null;
				}

			};
		}

		@Override
		public void remove() {
		}

	}

}
